package com.wutma.system.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.wutma.common.core.constants.Constants;
import com.wutma.common.core.enums.ResultCode;
import com.wutma.common.security.exception.ServiceException;
import com.wutma.system.domain.question.dto.QuestionAddDTO;
import com.wutma.system.domain.question.dto.QuestionEditDTO;
import com.wutma.system.domain.question.dto.QuestionQueryDTO;
import com.wutma.system.domain.question.entity.Question;
import com.wutma.system.domain.question.vo.QuestionDetailVO;
import com.wutma.system.domain.question.vo.QuestionESVO;
import com.wutma.system.domain.question.vo.QuestionVO;
import com.wutma.system.manager.QuestionCacheManager;
import com.wutma.system.mapper.question.QuestionMapper;
import com.wutma.system.service.question.QuestionService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RestHighLevelClient esClient;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {

        if (StringUtil.isNotEmpty(questionQueryDTO.getExcludeIdStr())) {
            String[] excludes = questionQueryDTO.getExcludeIdStr().split(Constants.SPLIT_SAM);
            Set<Long> excludeSet = Arrays.stream(excludes).map(Long::valueOf).collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeSet);
        }
        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        return questionMapper.selectQuestionList(questionQueryDTO);
    }

    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {

        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>().eq(Question::getTitle, questionAddDTO.getTitle()));
        if (CollectionUtil.isNotEmpty(questionList)) {
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        Question question = new Question();
        BeanUtil.copyProperties(questionAddDTO, question);
        int insert = questionMapper.insert(question);
        if (insert <= 0) {
            return false;
        }
        QuestionESVO questionESVO = new QuestionESVO();
        BeanUtil.copyProperties(question, questionESVO);
        saveQuestionES(questionESVO);
        questionCacheManager.questionIdAddCache(questionESVO.getQuestionId());
        return true;
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = getQuestionById(questionId);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public boolean edit(QuestionEditDTO questionEditDTO) {
        Question oldQuestion = getQuestionById(questionEditDTO.getQuestionId());
        updateQuestion(questionEditDTO, oldQuestion);
        int update = questionMapper.updateById(oldQuestion);
        if (update <= 0) {
            return false;
        }
        QuestionESVO questionESVO = new QuestionESVO();
        BeanUtil.copyProperties(oldQuestion, questionESVO);
        saveQuestionES(questionESVO);
        return true;
    }

    private void saveQuestionES(QuestionESVO questionESVO) {
        try {
            // 创建 IndexRequest
            String jsonString = JSON.toJSONString(questionESVO);
            IndexRequest indexRequest = new IndexRequest(Constants.ES_INDEX)
                    .id(String.valueOf(questionESVO.getQuestionId())) // 设置文档 ID，通常使用业务主键
                    .source(jsonString, XContentType.JSON); // 设置文档内容
            esClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new ServiceException(ResultCode.ES_SAVE_FAILURE);
        }
    }

    @Override
    public boolean delete(Long questionId) {
        try {
            getQuestionById(questionId);
            int delete = questionMapper.deleteById(questionId);
            if (delete <= 0) {
                return false;
            }
            // 索引库删除数据
            DeleteRequest deleteRequest = new DeleteRequest(Constants.ES_INDEX, questionId.toString());
            esClient.delete(deleteRequest, RequestOptions.DEFAULT);
            questionCacheManager.questionIdDeleteCache(questionId);
            return true;
        } catch (IOException e) {
            throw new ServiceException(ResultCode.ES_DELETE_FAILURE);
        }
    }

    private Question getQuestionById(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return question;
    }

    private void updateQuestion(QuestionEditDTO questionEditDTO, Question oldQuestion) {
        oldQuestion.setTitle(questionEditDTO.getTitle());
        oldQuestion.setDifficulty(questionEditDTO.getDifficulty());
        oldQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldQuestion.setContent(questionEditDTO.getContent());
        oldQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldQuestion.setMainFuc(questionEditDTO.getMainFuc());
    }
}
